package com.leyou.auth.service;

import com.leyou.auth.client.UserClient;
import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.mapper.UserMapper;
import com.leyou.auth.pojo.UserInfo;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.utils.CodecUtils;
import com.leyou.user.pojo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

@Service
@EnableConfigurationProperties(JwtProperties.class)
public class AuthService {
    private static Logger logger = LoggerFactory.getLogger(AuthService.class);

    @Autowired
    private JwtProperties jwtProp;
/*
    @Autowired
    private UserClient userClient;

    public String authentication(String username, String password) {
        try{
            //获得用户信息
            User user = userClient.login(username, password);
            if(user==null){
                logger.info("用户信息不存在，{}", username);
                return null;
            }
            //生成token
            String token = JwtUtils.generateToken(new UserInfo(user.getId(), user.getUsername()), jwtProp.getPrivateKey(), jwtProp.getExpire());
            return token;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }*/

    @Autowired
    private UserMapper userMapper;

    public String authentication(String username, String password) {
        try {
            // 查询
            User record = new User();
            record.setUsername(username);
            User user = this.userMapper.selectOne(record);

            if (user == null) {
                logger.info("用户信息不存在，{}", username);
                return null;
            }

            // 校验密码
            if (!user.getPassword().equals(CodecUtils.md5Hex(password, user.getSalt()))) {
                return null;
            }

            // 生成token
            UserInfo userInfo = new UserInfo(user.getId(), user.getUsername());
            String token = JwtUtils.generateToken(userInfo, jwtProp.getPrivateKey(), jwtProp.getExpire());

            return token;
        } catch (Exception e) {
            return null;
        }
    }

}
